from types import NoneType
from flask import jsonify
from datetime import datetime, timedelta


class ERRORCODES:
    # 成功状态码 (2xx)
    OK = 0, 200                     # 请求成功
    CREATED = 201, 201              # 资源创建成功
    ACCEPTED = 202, 202             # 请求已接受，但尚未处理完成
    NO_CONTENT = 204, 204           # 请求成功，无返回内容
    
    # 客户端错误码 (4xx)
    BAD_REQUEST = 400, 400          # 请求格式错误
    UNAUTHORIZED = 401, 401         # 未认证或认证失败
    FORBIDDEN = 403, 403            # 无权限访问
    NOT_FOUND = 404, 404            # 资源不存在
    METHOD_NOT_ALLOWED = 405, 405   # 请求方法不允许
    NOT_ACCEPTABLE = 406, 406       # 请求不可接受
    CONFLICT = 409, 409             # 资源冲突
    WX_LOGIN_FAILED = 410, 410       # 微信登录失败
    
    # 服务器错误码 (5xx)a
    INTERNAL_SERVER_ERROR = 500, 500 # 服务器内部错误
    SERVICE_UNAVAILABLE = 503, 503   # 服务不可用
    
    # 自定义业务错误码 (1000+)
    MISSING_PARAMETERS = 1001, 400   # 缺少必要参数
    INVALID_AUTH_INFO = 1002, 401    # 认证信息无效
    UNMATCHED_SIGNATURE = 1003, 401  # 签名不匹配
    EXHAUSTED_REFRESH_TIMES = 1004, 403  # 刷新次数已用尽
    INVALID_DATA_FORMAT = 1005, 400   # 数据格式无效
    DEVICE_NOT_FOUND = 1006, 404     # 设备不存在
    USER_EXISTS = 1007, 409          # 用户已存在
    WEAK_PASSWORD = 1008, 400        # 密码强度不足


def respond(
    data: dict | NoneType = None, message="请求成功。", error_code=ERRORCODES.OK
):
    return jsonify(
        {"status": error_code[0], "message": message, "data": data}
    ), error_code[1]


class Cache:
    cache = {}

    @classmethod
    def set(cls, key, value, expire_seconds):
        cls.cache[key] = {
            "value": value,
            "expires": datetime.now() + timedelta(seconds=expire_seconds),
        }

    @classmethod
    def get(cls, key):
        if key in cls.cache:
            entry = cls.cache[key]
            if entry["expires"] > datetime.now():
                return entry["value"]
            else:
                del cls.cache[key]
        return None

    @classmethod
    def delete(cls, key):
        if key in cls.cache:
            del cls.cache[key]

    @classmethod
    def clear(cls):
        cls.cache.clear()
